package com.lagou.user.service.impl;

import com.lagou.user.service.UserService;
import com.lagou.user.client.CodeFeignClient;
import com.lagou.user.dao.UserDao;
import com.lagou.user.dao.entity.User;
import java.util.Optional;
import java.util.UUID;

import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;


@Component
public class UserServiceImpl implements UserService {

  @Autowired
  private CodeFeignClient codeFeignClient;

  @Autowired
  private UserDao userDao;

  @Autowired
  private RedisTemplate<String, String> redisTemplate;

  @Override
  public Boolean register(String email, String password, String code, HttpServletResponse response) {
    // 校验验证码是否正确
    Integer codeValid = codeFeignClient.validateCode(email, code);
    if (!codeValid.equals(0)) {
      return false;
    }

    Boolean isRegister = isRegister(email);
    if (isRegister) {
      return false;
    }

    // 保存注册数据
    User user = new User();
    user.setUsername(email);
    user.setPassword(password);
    userDao.save(user);
    // 生成token
    String token = generateToken();
    redisTemplate.opsForValue().set(token, user.getUsername());
    Cookie cookie = new Cookie("token", token);
    response.addCookie(cookie);
    return true;
  }

  @Override
  public Boolean isRegister(String email) {
    // 查询对应email的用户数据
    Optional<User> userOptional = getUser(email);
    return userOptional.isPresent();
  }

  @Override
  public String login(String email, String password, HttpServletResponse response) {
    // 查询用户，进行密码匹配
    Optional<User> userOptional = getUser(email);
    if (!userOptional.isPresent()) {
      return "";
    }

    User user = userOptional.get();
    if (!user.getPassword().equals(password)) {
      return "";
    }

    // 生成token
    String token = generateToken();
    redisTemplate.opsForValue().set(token, user.getUsername());
    Cookie cookie = new Cookie("token",token);
    cookie.setPath("/");
    response.addCookie(cookie);
    return user.getUsername();
  }

  @Override
  public String userInfo(String token) {
    return redisTemplate.opsForValue().get(token);
  }

  private String generateToken() {
    return UUID.randomUUID().toString();
  }

  private Optional<User> getUser(String email) {
    User user = new User();
    user.setUsername(email);
    Example<User> example =  Example.of(user);
    return userDao.findOne(example);
  }
}
